package cn.huangyunxing.yxapiinterface.controller;


import cn.huangyunxing.common.model.entity.UserInterfaceInfo;
import cn.huangyunxing.common.service.InnerInterfaceInfoService;
import cn.huangyunxing.common.service.InnerUserInterfaceInfoService;
import cn.huangyunxing.common.service.InnerUserService;
import cn.huangyunxing.yxapiclientsdk.model.User;
import cn.huangyunxing.yxapiclientsdk.utils.SignUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

/**
 * 名称 API
 * @author HuangXing
 */
@RestController
@RequestMapping("/name")
public class NameController {

    @Resource
    private InnerInterfaceInfoService innerInterfaceInfoService;

    @Resource
    private InnerUserInterfaceInfoService innerUserInterfaceInfoService;

    @Resource
    private InnerUserService innerUserService;

    @GetMapping("/get")
    public String getNameByGet(String name, HttpServletRequest request) {
        System.out.println(request.getHeader("yupi"));
        return "GET 你的名字是" + name;
    }

    @PostMapping("/post")
    public String getNameByPost(@RequestParam String name) {
        return "POST 你的名字是" + name;
    }

    @PostMapping("/user")
    public String getUsernameByPost(@RequestBody User user, HttpServletRequest request) {
        String accessKey = request.getHeader("accessKey");
        String nonce = request.getHeader("nonce");
        String timestamp = request.getHeader("timestamp");
        String sign = request.getHeader("sign");
        String body = request.getHeader("body");

       // 实际情况应该是去数据库中查是否已分配给用户
        cn.huangyunxing.common.model.entity.User user1 = new cn.huangyunxing.common.model.entity.User();
        String accessKey1 = user1.getAccessKey();
        String secretKey = user1.getSecretKey();
        if (!accessKey.equals(accessKey1)) {
            throw new RuntimeException("无权限");
        }
        //todo 可以用redis或者hashmap存储
//        if (Long.parseLong(nonce) > 10000) {
//            throw new RuntimeException("无权限");
//        }
        //  时间和当前时间不能超过 5 分钟
        LocalDateTime now = LocalDateTime.now();
        long between = ChronoUnit.MINUTES.between(LocalDateTime.parse(timestamp), now);
        if (between > 5) {
            throw new RuntimeException("时间已过期");
        }
        // 实际情况中是从数据库中查出 secretKey
        String serverSign = SignUtils.genSign(body,secretKey );
        if (!sign.equals(serverSign)) {
            throw new RuntimeException("无权限");
        }
        // todo 调用次数 + 1 invokeCount

        String result = "POST 用户名字是" + user.getUsername();
        return result;
    }
}
